package com.pipayshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pipayshop.entity.*;
import com.pipayshop.entity.dto.RebateDTO;
import com.pipayshop.entity.vo.ResponseVO;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.*;
import com.pipayshop.service.RebateService;
import com.pipayshop.service.UserAccountInfoService;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class RebateServiceImpl implements RebateService {

    @Autowired
    ZoneLeaderConfigurationMapper zoneLeaderConfigurationMapper;
    @Autowired
    FirstZoneMapper firstZoneMapper;
    @Autowired
    TwoZoneSuperiorMapper twoZoneSuperiorMapper;
    @Autowired
    UserByZoneMapper userByZoneMapper;
    @Resource
    private UserAccountInfoService accountInfoService;
    @Autowired
    LogLeaderCommissionMapper logLeaderCommissionMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVO<String> firstRebate(RebateDTO rebateDTO) {
        if (rebateDTO == null || StringUtils.isBlank(rebateDTO.getUserId()) || rebateDTO.getZoneId() == null) {
            throw new BusinessException("参数为空");
        }
        String userId = rebateDTO.getUserId();
        Long zoneId = rebateDTO.getZoneId();

        ZoneLeaderConfiguration zoneLeaderConfiguration = zoneLeaderConfigurationMapper.selectById(1);
        //查看返佣资格
        FirstZone firstZone = firstZoneMapper.selectOne(new QueryWrapper<FirstZone>()
                .eq("zone_id", zoneId));
        if (firstZone.getInvalid() == 1) {
            throw new BusinessException("rebate_group_invalid");
        }
        if (firstZone.getLevelRebate() == 1) {
            throw new BusinessException("rebate_already_issued");
        }
        if (firstZone.getRebateQualification() == 0) {
            throw new BusinessException("rebate_not_eligible_retry_later");
        }
        if (firstZone.getOpeningZoneTime().compareTo(firstZone.getEndTime()) >= 0) {
            firstZoneMapper.update(null, new UpdateWrapper<FirstZone>()
                    .eq("zone_id", zoneId)
                    .set("invalid", 1));
            throw new BusinessException("rebate_group_invalid");
        }
        //修改一级团状态为成功返利且团失效
        firstZoneMapper.update(null, new UpdateWrapper<FirstZone>()
                .eq("zone_id", zoneId)
                .set("level_rebate", 1)
                .set("invalid", 1));
        //为用户账户添加金额
        UserByZone userByZone = userByZoneMapper.selectOne(new QueryWrapper<UserByZone>()
                .eq("user_id", userId));
        BigDecimal interestRate = userByZone.getUserThreshold()
                .multiply(BigDecimal.valueOf(zoneLeaderConfiguration.getFirstInterestRate()));

        accountInfoService.addPiAccount(userId, interestRate);

        //修改用户专区信息表
        Integer firstRebateNum = userByZoneMapper.selectOne(new QueryWrapper<UserByZone>()
                .eq("user_id", userId)).getFirstRebateNum();
        userByZoneMapper.update(null, new UpdateWrapper<UserByZone>()
                .eq("user_id", userId)
                .set("first_rebate_num", firstRebateNum + 1));
        //添加用户返佣记录表
        logCommission(userId, zoneId, interestRate);

        return ResponseVO.getSuccessResponseVo("一级返利成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVO<String> twoRebate(RebateDTO rebateDTO) {
        if (rebateDTO == null || StringUtils.isBlank(rebateDTO.getUserId()) || rebateDTO.getZoneId() == null) {
            throw new BusinessException("参数为空");
        }
        String userId = rebateDTO.getUserId();
        Long zoneId = rebateDTO.getZoneId();

        UserByZone userByZone = userByZoneMapper.selectOne(new QueryWrapper<UserByZone>()
                .eq("user_id", userId));
        ZoneLeaderConfiguration zoneLeaderConfiguration = zoneLeaderConfigurationMapper.selectById(1);

        //查看返佣资格
        TwoZoneSuperior twoZoneSuperior = twoZoneSuperiorMapper.selectOne(new QueryWrapper<TwoZoneSuperior>()
                .eq("zone_id", zoneId));

        validateRebateEligibility(twoZoneSuperior, zoneId);

        twoZoneSuperiorMapper.update(null, new UpdateWrapper<TwoZoneSuperior>()
                .eq("zone_id", twoZoneSuperior.getZoneId())
                .set("level_rebate", 1)
                .set("invalid", 1));

        BigDecimal interestRate = null;
        if (twoZoneSuperior.getIsTwoRebateTime() == 1) {
            //开团时间
            Date openingZoneTime = twoZoneSuperior.getOpeningZoneTime();
            //一阶段结束时间
            Date endTimeOne = twoZoneSuperior.getEndTimeOne();
            if (openingZoneTime.compareTo(endTimeOne) <= 0) {
                //为用户账户添加金额
                interestRate = userByZone.getUserThreshold()
                        .multiply(BigDecimal.valueOf(zoneLeaderConfiguration.getFirstInterestRate()));
            } else {
                interestRate = userByZone.getUserThreshold()
                        .multiply(BigDecimal.valueOf(zoneLeaderConfiguration.getTwoInterestRate()));
            }
            accountInfoService.addPiAccount(userId, interestRate);
        } else {
            //开团时间
            Date openingZoneTime = twoZoneSuperior.getOpeningZoneTime();
            //结束时间
            Date endTimeOne = twoZoneSuperior.getEndTimeOne();
            if (openingZoneTime.compareTo(endTimeOne) <= 0) {
                //为用户账户添加金额
                interestRate = userByZone.getUserThreshold()
                        .multiply(BigDecimal.valueOf(zoneLeaderConfiguration.getFirstInterestRate()));
                accountInfoService.addPiAccount(userId, zoneLeaderConfiguration.getThresholdSum()
                        .multiply(BigDecimal.valueOf(zoneLeaderConfiguration.getFirstInterestRate())));
            }
        }
        //修改用户专区信息表
        updateUserZoneInfo(userId);
        logCommission(userId, zoneId, interestRate);

        return ResponseVO.getSuccessResponseMsg(null, "二级返佣成功");
    }

    private void validateRebateEligibility(TwoZoneSuperior twoZone, Long zoneId) {
        if (twoZone.getInvalid() == 1) {
            throw new BusinessException("rebate_group_invalid");
        }
        if (twoZone.getLevelRebate() == 1) {
            throw new BusinessException("rebate_already_received");
        }
        if (twoZone.getRebateQualification() == 0) {
            throw new BusinessException("rebate_not_eligible_retry_10min");
        }
        // 如果时间超出，标记团失效
        if ((twoZone.getIsTwoRebateTime() == 1 && twoZone.getOpeningZoneTime().compareTo(twoZone.getEndTimeTwo()) >= 0) ||
                (twoZone.getIsTwoRebateTime() == 0 && twoZone.getOpeningZoneTime().compareTo(twoZone.getEndTimeOne()) >= 0)) {
            twoZoneSuperiorMapper.update(null, new UpdateWrapper<TwoZoneSuperior>()
                    .eq("zone_id", zoneId)
                    .set("invalid", 1));
            throw new BusinessException("rebate_group_invalid");
        }
    }

    private void updateUserZoneInfo(String userId) {
        Integer twoRebateNum = userByZoneMapper.selectOne(new QueryWrapper<UserByZone>().eq("user_id", userId))
                .getTwoRebateNum();
        userByZoneMapper.update(null, new UpdateWrapper<UserByZone>()
                .eq("user_id", userId)
                .set("two_rebate_num", twoRebateNum + 1));
    }

    private void logCommission(String userId, Long zoneId, BigDecimal interestRate) {
        LogLeaderCommission log = new LogLeaderCommission();
        log.setZoneLeaderId(userId);
        log.setZoneId(zoneId);
        log.setCommissionAmount(interestRate);
        logLeaderCommissionMapper.insert(log);
    }

}
